package com.security.service;

import com.common.result.Result;
import com.common.util.StringUtil;
import com.security.util.RpcUtil;
import lombok.Builder;
import lombok.Data;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 负责与认证中心通信的service
 *
 * @author 大忽悠
 * @create 2022/10/11 20:51
 */
@Data
public class AuthenticateService {
    private final AuthenticateUrlManager authenticateUrlManager;

    public AuthenticateService(AuthenticateUrlManager authenticateUrlManager) {
        this.authenticateUrlManager = authenticateUrlManager;
    }

    /**
     * @param id   用户id
     * @param name 用户姓名
     * @return token
     */
    public Result generatorToken(Integer id, String name) {
        return RpcUtil.postParams(authenticateUrlManager.getGeneratorTokenUrl(), Map.of("id",id,"name",name),new Result());
    }

    /**
     * @param token
     * @return 如果token认证成功, 返回UserDetails, 并且响应头中返回了刷新后的token, 解析失败返回null
     */
    public Result verifyToken(String token) {
        return RpcUtil.postParams(authenticateUrlManager.getVerifyTokenUrl(),Map.of("token",token),new Result());
    }

    /**
     * @param url 用户请求url
     * @return 访问当前请求需要具备哪些角色
     */
    public Result getRolesOfRequestUrl(String url) {
        return RpcUtil.postParams(authenticateUrlManager.getRolesOfRequestUrl(),Map.of("url",url),new Result());
    }

    /**
     * 向注册中心同步新注册的用户信息,默认不同步密码
     *
     * @param username
     * @param password
     */
    public void addUser(String username, String password, String... roleList) {
        Result result = RpcUtil.postObj(authenticateUrlManager.getAddUserUrl(), UserForJson.builder()
                .username(username).accountNonExpired(true).accountNonLocked(true).credentialsNonExpired(true).enabled(true).password(password).build(),new Result());
        if(ObjectUtils.isEmpty(roleList)){
            return;
        }
        //为用户赋予角色
        RpcUtil.postParams(authenticateUrlManager.getReleaseRoleToUserUrl(),Map.of("uid",result.getData(),"roleNameList",String.join(StringUtil.DELIMITER, roleList)),new Result());
    }

    public void updateUsername(String oldUsername, String newUsername) {
        RpcUtil.postParams(authenticateUrlManager.getUpdateUserNameUrl(), Map.of("oldUsername", oldUsername,"newUsername", newUsername),new Result());
    }

    public void delUser(String username) {
        RpcUtil.delUrlVariable(authenticateUrlManager.getDelUserUrl(),username);
    }

    @Builder
    @Data
    private static class UserForJson {
        private String username;
        private String password;
        private Boolean enabled;
        private Boolean accountNonExpired;
        private Boolean accountNonLocked;
        private Boolean credentialsNonExpired;
    }
}
